import { createRouter, createWebHistory } from "vue-router";
import Cookie from "js-cookie";
import { useMenuStore } from "@/stores/menu";
import initRoutes from "./initRoute";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: initRoutes,
});

router.beforeEach(async (to, from, next) => {
  const { getMenus, logout, menusList } = useMenuStore();
  const token = Cookie.get("token");
  if (token) {
    if (to.path === "/login") {
      next("/");
    } else {
      if(menusList.length > 0) {
        next()
      } else {
        try{
          await getMenus()
          next({...to})
        }catch(error) {
          logout()
          next('/login')
        }
      }
    }
  } else {
    if (!to.meta.required) {
      next();
    } else {
      next("/login");
    }
  }
});

export default router;
